/* eslint-disable react-hooks/exhaustive-deps */
import { getChannel } from '@/store/actions/channels'

import { getArticle, delAritcle } from '@/store/actions/article'
import defaultImg from '@/assets/error.png'
import STATUS from '@/components/constant/status'
import {
  Card,
  Breadcrumb,
  Radio,
  Form,
  Button,
  Select,
  DatePicker,
  Table,
  Space,
  Image,
  Tag,
  Popconfirm,
  message
} from 'antd'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import React, { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Link, useHistory } from 'react-router-dom'

const { Option } = Select
const { RangePicker } = DatePicker
export default function List () {
  const history = useHistory()
  const dispatch = useDispatch()
  // 查询 条件
  const refParams = useRef({})

  useEffect(() => {
    // 获取频道的下拉列表数据
    dispatch(getChannel())

    // 获取文章列表数据
    dispatch(getArticle())
  }, [])
  // 频道数据
  const channelList = useSelector((state) => state.channels)
  // 文章列表数据
  const {
    results: dataSource,
    total_count: total,
    page: current,
    per_page: pageSize
  } = useSelector((state) => state.article)

  const onFinish = (values) => {
    const params = refParams.current
    params.status = values.status
    params.channel_id = values.channel_id
    if (values.status !== -1) {
      params.status = values.status
    }
    params.begin_pubdate = values.date[0]
      .startOf('day')
      .format('YYYY-MM-DD HH:mm:ss')
    params.end_pubdate = values.date[1]
      .startOf('day')
      .format('YYYY-MM-DD HH:mm:ss')
    console.log('表单数据', params)
    // 获取文章列表数据
    dispatch(getArticle(params))
  }
  // 页码或者pageSize改变回调，参数是改变后的页码及每页条数
  const onChange = (page, pageSize) => {
    const params = refParams.current
    console.log(page, pageSize)
    // 在原来查询条件基础上 去补充page,per_page
    params.page = page
    params.per_page = pageSize

    // 获取文章列表数据
    dispatch(getArticle(params))
  }
  // 删除功能部分
  const del = async (id) => {
    try {
      await dispatch(delAritcle(id))
      message.success('删除成功')
      // 获取文章列表数据
      dispatch(getArticle(refParams.current))
    } catch (err) {}
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render (cover) {
        console.log(cover)
        if (cover.type) {
          return (
            <Image
              width={120}
              height={120}
              src={cover.images[0]}
              fallback=""
            />
          )
        } else {
          return <Image width={120} height={120} src={defaultImg} />
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render (status) {
        const res = STATUS.find((it) => it.id === status)
        if (res) {
          return <Tag color={res.color}>{res.title}</Tag>
        } else {
          return <Tag color="#f50">{res.title}</Tag>
        }
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count'
    },
    {
      title: '操作',
      dataIndex: 'cover',
      render (_, row) {
        // console.log(row.id)
        return (
          <Space>
            <Button
              onClick={() => {
                history.push('/home/publish/' + row.id)
              }}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            />
            <Popconfirm
              onConfirm={() => del(row.id)}
              title="确认删除吗？"
              okText="是的"
              cancelText="取消">
              <Button
                type="primary"
                shape="circle"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表 </Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form name="control-hooks" onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select placeholder="请选择频道" style={{ width: 200 }}>
              {channelList.map((it) => (
                <Option key={it.id} value={it.id}>
                  {it.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到${total}条结果:`} style={{ marginTop: 10 }}>
        <Table
          pagination={{
            pageSize,
            current,
            total,
            onChange
          }}
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
        />
      </Card>
      {/* 表格 */}
    </div>
  )
}
